# 业务逻辑函数
import sys
import multiprocessing
from time import sleep

from .server import Orin
from .config import settings

from .utils.stop_ps import StopPs
from .utils.my_threading import MyThread
from .utils.disk_used import userd
from .command import task_command


class RunServer(object):
    def __init__(self):
        self.orin01_pid_list = []
        self.orin02_pid_list = []
        self.stop_ps = StopPs()
        pass

    def __del__(self):
        # 对象销毁时结束进程
        # 获取进程号然后销毁
        pass

    def orin_one(self):

        with Orin(
            ip=settings.on_01,
            username=settings.username,
            password=settings.password,
            type=settings.ps_name,
        ) as self.orin:

            # 获取run.sh进程号
            orin01_th = MyThread(
                self.orin,
                settings.ps_name,
                target=task_command,
                args=[self.orin, "action_80.sh", "orin01"],
            )
            orin01_th.start()

            self.orin01_pid_list.extend(orin01_th.get_id_list())

            # 根据磁盘用量判断是否正常
            userd(self.orin, "orin01")

            orin01_th.join()

    def orin_two(self):
        with Orin(
            ip=settings.on_02,
            username=settings.username,
            password=settings.password,
            type=settings.ps_name,
        ) as self.orin:

            orin02_th = MyThread(
                self.orin,
                settings.ps_name,
                target=task_command,
                args=[self.orin, "action_81.sh", "orin02"],
            )
            orin02_th.start()

            self.orin02_pid_list.extend(orin02_th.get_id_list())

            # 根据磁盘用量判断是否正常
            userd(self.orin, "orin02")

            orin02_th.join()

    def running(self):
        orin01_ps = multiprocessing.Process(target=self.orin_one, daemon=True)
        orin02_ps = multiprocessing.Process(target=self.orin_two, daemon=True)

        orin01_ps.start()
        orin02_ps.start()

        sleep(4)
        while True:
            shop = input("\n回车停止采集进程\n") or "y"
            if shop == "y":
                self.stop_ps.kill_orin(
                    ip=settings.on_01,
                    ps_list=self.stop_ps.get_id_list(ip=settings.on_01, type=settings.ps_name),
                )
                self.stop_ps.kill_orin(
                    ip=settings.on_02,
                    ps_list=self.stop_ps.get_id_list(ip=settings.on_02, type=settings.ps_name),
                )
                print("\n采集停止")
                sys.exit()
